<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="计划编号">
              <a-input placeholder="请输入计划编号" v-model="queryParam.planNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="计划名称">
              <a-input placeholder="请输入计划名称" v-model="queryParam.planName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="plan_status" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('生产计划')">导出</a-button>
      <a-button type="primary" icon="upload" @click="handleImportExcel">导入</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a> 项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <template slot="planType" slot-scope="text">
          <a-tag v-if="text == 1" color="blue">模板生成</a-tag>
          <a-tag v-else-if="text == 2" color="green">自定义创建</a-tag>
        </template>

        <template slot="status" slot-scope="text">
          <a-tag v-if="text == 0" color="orange">待审核</a-tag>
          <a-tag v-else-if="text == 1" color="blue">已审核</a-tag>
          <a-tag v-else-if="text == 2" color="cyan">已下发</a-tag>
          <a-tag v-else-if="text == 3" color="purple">已领取</a-tag>
          <a-tag v-else-if="text == 4" color="brown">生产中</a-tag>
          <a-tag v-else-if="text == 5" color="green">已完成</a-tag>
          <a-tag v-else-if="text == 6" color="error">已取消</a-tag>
        </template>

        <template slot="priority" slot-scope="text">
          <a-tag v-if="text == 1" color="green">低</a-tag>
          <a-tag v-else-if="text == 2" color="orange">中</a-tag>
          <a-tag v-else-if="text == 3" color="red">高</a-tag>
        </template>

        <template slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)" v-if="record.status <= 1">编辑</a>
          <a-divider type="vertical" v-if="record.status <= 1" />
          <a @click="handleApprove(record)" v-if="record.status == 0">审核</a>
          <a-divider type="vertical" v-if="record.status == 0" />
          <a @click="handleIssue(record)" v-if="record.status == 1">下发</a>
          <a-divider type="vertical" v-if="record.status == 1" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" v-if="record.status <= 1">
            <a style="color: red">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>

    <plan-modal ref="modalForm" @ok="modalFormOk"></plan-modal>
    <plan-detail-modal ref="detailModal"></plan-detail-modal>
    <plan-approve-modal ref="approveModal" @ok="modalFormOk"></plan-approve-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import PlanModal from './modules/PlanModal'
import PlanDetailModal from './modules/PlanDetailModal'
import PlanApproveModal from './modules/PlanApproveModal'
import { createInboundByOrder } from '@/api/wms/finishedGoodsInbound'

export default {
  name: 'PlanList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    PlanModal,
    PlanDetailModal,
    PlanApproveModal,
  },
  data() {
    return {
      description: '生产计划管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '计划编号',
          align: 'center',
          dataIndex: 'planNo',
        },
        {
          title: '计划名称',
          align: 'center',
          dataIndex: 'planName',
        },
        {
          title: '关联订单',
          align: 'center',
          dataIndex: 'orderNo',
        },
        {
          title: '计划类型',
          align: 'center',
          dataIndex: 'planType',
          scopedSlots: { customRender: 'planType' },
        },
        {
          title: '计划数量',
          align: 'center',
          dataIndex: 'planQuantity',
        },
        {
          title: '实际数量',
          align: 'center',
          dataIndex: 'actualQuantity',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '优先级',
          align: 'center',
          dataIndex: 'priority',
          scopedSlots: { customRender: 'priority' },
        },
        {
          title: '计划负责人',
          align: 'center',
          dataIndex: 'planManager',
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 200,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/mes/plan/list',
        delete: '/mes/plan/delete',
        deleteBatch: '/mes/plan/deleteBatch',
        exportXlsUrl: '/mes/plan/exportXls',
        importExcelUrl: 'mes/plan/importExcel',
        approve: '/mes/plan/approve',
        issue: '/mes/plan/issue',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'planNo', text: '计划编号' })
      fieldList.push({ type: 'string', value: 'planName', text: '计划名称' })
      fieldList.push({ type: 'string', value: 'orderNo', text: '关联订单编号' })
      fieldList.push({ type: 'int', value: 'planType', text: '计划类型' })
      fieldList.push({ type: 'int', value: 'planQuantity', text: '计划数量' })
      fieldList.push({ type: 'int', value: 'status', text: '状态' })
      fieldList.push({ type: 'int', value: 'priority', text: '优先级' })
      fieldList.push({ type: 'string', value: 'planManager', text: '计划负责人' })
      this.superFieldList = fieldList
    },
    handleDetail: function (record) {
      this.$refs.detailModal.show(record)
    },
    handleApprove: function (record) {
      this.$refs.approveModal.show(record)
    },
    handleIssue: function (record) {
      let that = this
      this.$confirm({
        title: '确认操作',
        content: '是否确定下发该生产计划？',
        onOk: function () {
          that.doIssue(record.id)
        },
      })
    },
    doIssue: function (planId) {
      let that = this
      this.$http.post(this.url.issue, {}, { params: { planId: planId } }).then((res) => {
        if (res.success) {
          that.$message.success('下发成功！')
          that.loadData()

          // 获取计划详情以获取订单编号
          const planRecord = that.dataSource.find((item) => item.id === planId)
          if (planRecord && planRecord.orderNo) {
            // 调用成品入库单生成API
            that.createFinishedGoodsInbound(planRecord.orderNo, planId)
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    // 创建成品入库单
    createFinishedGoodsInbound: function (orderNo, planId) {
      let that = this
      const params = {
        orderNo: orderNo,
        productionPlanId: planId,
      }
      createInboundByOrder(params)
        .then((res) => {
          if (res.success) {
            that.$message.success('成品入库单创建成功！')
          } else {
            that.$message.warning('成品入库单创建失败：' + res.message)
          }
        })
        .catch((error) => {
          console.error('创建成品入库单失败:', error)
          that.$message.error('成品入库单创建失败，请检查网络连接')
        })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
